﻿using System;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Windows;
using System.Windows.Navigation;
using desarrolloMobile.DGTViewer.ViewModels;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Phone.Data.Entity;

namespace desarrolloMobile.DGTViewer
{
    public partial class App
    {
        private static DgtContexto _viewModel;

        private readonly IsolatedStorageSettings _settings
            = IsolatedStorageSettings.ApplicationSettings;

        private static string _pValor = string.Empty;
        private static string _pCampo = string.Empty;
        private static bool _pFuente = true;

        /// <summary>
        /// A static ViewModel used by the views to bind against.
        /// </summary>
        /// <returns>The MainViewModel object.</returns>
        public static DgtContexto ViewModel
        {
            get
            {
                _viewModel = _viewModel.TryGetNewInstance(_pValor, _pCampo,_pFuente);

                return _viewModel;
            }
        }

        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public PhoneApplicationFrame RootFrame { get; private set; }

        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions. 
            UnhandledException += Application_UnhandledException;

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode, 
                // which shows areas of a page that are being GPU accelerated with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;


            }

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

        }

        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            if (_settings.Contains("PredicadoValor"))
                _pValor = _settings["PredicadoValor"] as string;

            if (_settings.Contains("PredicadoCampo"))
                _pCampo = _settings["PredicadoCampo"] as string;
            
            if (_settings.Contains("Fuente"))
                _pFuente = (bool)_settings["Fuente"];
        }


        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
            // Ensure that application state is restored appropriately
            if (!ViewModel.IsDataLoaded)
            {
                _pCampo = PhoneApplicationService.Current
                    .State["PredicadoCampo"].ToString();

                _pValor = PhoneApplicationService.Current
                    .State["PredicadoValor"].ToString();

                _pFuente = (bool)PhoneApplicationService.Current
                            .State["Fuente"];

                _viewModel = _viewModel.GetNewInstance(_pValor, _pCampo, _pFuente);


                _viewModel.Hora = (DateTime)
                                  PhoneApplicationService.Current
                                      .State["Hora"];
            
                var contexto = new ObjectContext("DatosTotal");
                var query = contexto.CreateQuery<Incidencia>();
                var result = from c in query
                             select c;

                _viewModel.IncidenciasTotal = result.ToObservableCollection();

                contexto = new ObjectContext("Datos");
                query = contexto.CreateQuery<Incidencia>();
                result = from c in query
                             select c;
                _viewModel.Incidencias = result.ToObservableCollection();
            }
        }

        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
            var vivStore = new ObjectStore("DatosTotal");
            vivStore.Persist(_viewModel.IncidenciasTotal);
            var vivStore2 = new ObjectStore("Datos");
            vivStore2.Persist(_viewModel.Incidencias);

            PhoneApplicationService.Current.State.Clear();
            PhoneApplicationService.Current
                .State.Add("Hora", _viewModel.Hora);
            PhoneApplicationService.Current
                .State.Add("PredicadoValor", _viewModel.PredicadoValor);
            PhoneApplicationService.Current
                .State.Add("PredicadoCampo", _viewModel.PredicadoCampo);
            PhoneApplicationService.Current
                .State.Add("Fuente", _viewModel.DGT);
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
            _settings.Clear();

            if (_viewModel != null)
            {
                if (_viewModel.PredicadoValor.IsValid())
                    _settings.Add("PredicadoValor", _viewModel.PredicadoValor);
                else
                    _settings.Remove("PredicadoValor");

                if (_viewModel.PredicadoCampo.IsValid())
                    _settings.Add("PredicadoCampo", _viewModel.PredicadoCampo);
                else
                    _settings.Remove("PredicadoCampo");

                _settings.Add("Fuente",_viewModel.DGT);
            }
        }

        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        #region Phone application initialization

        // Avoid double-initialization
        private bool _phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (_phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            _phoneApplicationInitialized = true;
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        #endregion
    }
}